package org.summerframework.core.validation;

import org.summerframework.core.validation.constraints.SeparatorLength;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author liaorongbiao
 * @version 1.0
 * @date 2019-06-26 09:31
 **/
public class SeparatorLengthValidate implements ConstraintValidator<SeparatorLength, String> {

    private SeparatorLength separatorLength;

    @Override
    public void initialize(SeparatorLength constraintAnnotation) {
        this.separatorLength = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        final String[] split = StringUtils.split(value, separatorLength.separator());
        return split.length <= separatorLength.max() && split.length >= separatorLength.min();
    }
}
